<template>
  <div class="upload-file">
    <el-upload
      class="upload-file-uploader"
      action="/"
      :file-list="fileList"
      :limit="limit"
      :http-request="handleHttpRequest"
      :on-exceed="handleExceed"
      :on-remove="handleRemoveFile"
    >
      <!-- 上传按钮 -->
      <el-button size="mini" type="primary">选取文件</el-button>
      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">
          大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
        </template>
        <template v-if="fileType">
          格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
        </template>
        的文件
      </div>
    </el-upload>
  </div>
</template>

<script>
import Queue from "promise-queue-plus";
import axios from "axios";
import md5 from "@/utils/md5";
import { taskInfo, initTask, preSignUrl, merge } from "@/api/oss";
export default {
  name: "ShardUpload",
  props: {
    // 值
    value: [String, Object, Array],
    nameList: {
      type: Array,
      default: () => [],
    },
    // 数量限制
    limit: {
      type: Number,
      default: 5,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 500,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: [Array, Boolean],
      default: () => ["doc", "docx", "xls", "xlsx", "ppt", "txt", "pdf"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      fileList: [],
      fileUploadChunkQueue: {},
    };
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          let temp = 1;
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : this.value.split(",");
          // 然后将数组转为对象数组
          this.fileList = list.map((item, index) => {
            if (typeof item === "string") {
              item = { name: this.nameList[index] || item, url: item };
            }
            item.uid = item.uid || new Date().getTime() + temp++;
            return item;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    handleRemoveFile(uploadFile) {
      const index = this.fileList.findIndex((i) => i.uid === uploadFile.uid);
      if (index !== -1) {
        this.fileList.splice(index, 1);
        this.$emit("input", this.listToString(this.fileList));
      }
      const queueObject = this.fileUploadChunkQueue[uploadFile.uid];
      if (queueObject) {
        queueObject.stop();
        this.fileUploadChunkQueue[uploadFile.uid] = undefined;
      }
    },
    async getTaskInfo(file) {
      let task;
      const identifier = await md5(file);
      const { code, data, msg } = await taskInfo(identifier);
      if (code === 200) {
        task = data;
        if (!task) {
          const initTaskData = {
            identifier,
            fileName: file.name,
            totalSize: file.size,
            chunkSize: 6 * 1024 * 1024,
          };
          const { code, data, msg } = await initTask(initTaskData);
          if (code === 200) {
            task = data;
          } else {
            this.$notify({
              title: "文件上传错误",
              type: "error",
              message: msg,
            });
          }
        }
      } else {
        this.$notify({
          title: "文件上传错误",
          type: "error",
          message: msg,
        });
      }
      return task;
    },
    async handleUpload(file, taskRecord, options) {
      let lastUploadedSize = 0; // 上次断点续传时上传的总大小
      let uploadedSize = 0; // 已上传的大小
      const totalSize = file.size || 0; // 文件总大小
      let startMs = new Date().getTime(); // 开始上传的时间
      const { exitPartList, chunkSize, chunkNum, fileIdentifier } = taskRecord;

      // 获取从开始上传到现在的平均速度（byte/s）
      const getSpeed = () => {
        // 已上传的总大小 - 上次上传的总大小（断点续传）= 本次上传的总大小（byte）
        const intervalSize = uploadedSize - lastUploadedSize;
        const nowMs = new Date().getTime();
        // 时间间隔（s）
        const intervalTime = (nowMs - startMs) / 1000;
        return intervalSize / intervalTime;
      };

      const uploadNext = async (partNumber) => {
        const start = new Number(chunkSize) * (partNumber - 1);
        const end = start + new Number(chunkSize);
        const blob = file.slice(start, end);
        const { code, data, msg } = await preSignUrl({
          identifier: fileIdentifier,
          partNumber: partNumber,
        });
        if (code === 200 && data) {
          await axios.request({
            url: data,
            method: "PUT",
            data: blob,
            isShardUpload: true,
            headers: {
              "Content-Type": "application/octet-stream",
              isToken: false,
            },
          });
          return Promise.resolve({
            partNumber: partNumber,
            uploadedSize: blob.size,
          });
        }
        return Promise.reject(`分片${partNumber}， 获取上传地址失败`);
      };

      /**
       * 更新上传进度
       * @param increment 为已上传的进度增加的字节量
       */
      const updateProcess = (increment) => {
        increment = new Number(increment);
        const { onProgress } = options;
        let factor = 1000; // 每次增加1000 byte
        let from = 0;
        // 通过循环一点一点的增加进度
        while (from <= increment) {
          from += factor;
          uploadedSize += factor;
          const percent = Math.round((uploadedSize / totalSize) * 100).toFixed(
            2
          );
          onProgress({ percent: percent });
        }

        const speed = getSpeed();
        const remainingTime =
          speed != 0
            ? Math.ceil((totalSize - uploadedSize) / speed) + "s"
            : "未知";
        console.log(
          "剩余大小：",
          (totalSize - uploadedSize) / 1024 / 1024,
          "mb"
        );
        console.log("当前速度：", (speed / 1024 / 1024).toFixed(2), "mbps");
        console.log("预计完成：", remainingTime);
      };

      return new Promise((resolve) => {
        const failArr = [];
        const queue = Queue(5, {
          retry: 3, //Number of retries
          retryIsJump: false, //retry now?
          workReject: function (reason, queue) {
            failArr.push(reason);
          },
          queueEnd: function (queue) {
            resolve(failArr);
          },
        });

        this.fileUploadChunkQueue[file.uid] = queue;
        for (let partNumber = 1; partNumber <= chunkNum; partNumber++) {
          const exitPart = (exitPartList || []).find(
            (exitPart) => exitPart.partNumber == partNumber
          );
          if (exitPart) {
            // 分片已上传完成，累计到上传完成的总额中,同时记录一下上次断点上传的大小，用于计算上传速度
            lastUploadedSize += new Number(exitPart.size);
            updateProcess(exitPart.size);
          } else {
            queue.push(() =>
              uploadNext(partNumber).then((res) => {
                // 单片文件上传完成再更新上传进度
                updateProcess(res.uploadedSize);
              })
            );
          }
        }
        if (queue.getLength() == 0) {
          // 所有分片都上传完，但未合并，直接return出去，进行合并操作
          resolve(failArr);
          return;
        }
        queue.start();
      });
    },
    async handleHttpRequest(options) {
      const file = options.file;
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split(".");
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      if (file.size > this.size * 1024 * 1024) {
        this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
        return false;
      }
      const task = await this.getTaskInfo(file);
      if (task) {
        const { finished, path, originalFileName, taskRecord } = task;
        const { fileIdentifier: identifier } = taskRecord;
        if (finished) {
          const successFile = {
            name: originalFileName,
            url: path,
            fileSize: file.size,
          };
          this.fileList.push(successFile);
          this.$emit("input", this.listToString(this.fileList));
          this.$emit("uploadSuccess", successFile);
          return path;
        } else {
          const errorList = await this.handleUpload(file, taskRecord, options);

          if (errorList.length > 0) {
            this.$notify({
              title: "文件上传错误",
              type: "error",
              message: "部分分片上次失败，请尝试重新上传文件",
            });
            return;
          }
          const { code, data, msg } = await merge(identifier);
          if (code === 200) {
            const successFile = {
              name: originalFileName,
              url: path,
              fileSize: file.size,
            };
            this.fileList.push(successFile);
            this.$emit("input", this.listToString(this.fileList));
            this.$emit("uploadSuccess", successFile);
            return path;
          } else {
            this.$notify({
              title: "文件上传错误",
              type: "error",
              message: msg,
            });
          }
        }
      } else {
        this.$notify({
          title: "文件上传错误",
          type: "error",
          message: "获取上传任务失败",
        });
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
  },
};
</script>
